package com.yilin.tms.data.controller;

import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.MapUtil;
import com.yilin.commons.util.PdfUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.application.PlatRequest;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.annotation.Explain;
import com.yilin.tms.core.commons.annotation.NotNull;
import com.yilin.tms.core.commons.annotation.UserTarget;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.components.minio.FileDealUtil;
import com.yilin.tms.core.components.minio.MinIoUploadResDTO;
import com.yilin.tms.core.entity.data.contracted.ContractBody;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.data.service.IContractService;
import com.yilin.tms.data.service.IMinOssService;
import com.yilin.tms.data.service.impl.MinOssService;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.core.remote.IUserRemote;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * 合同控制器
 */
@RequestMapping(value = "/data/contract/")
@RestController
public class ContractController extends BaseController {
    @Value("${servlet.temporary-path}")
    String temporaryPath;
    
    @Resource
    IContractService contractService;
    @Resource
    IMinOssService minOssService;

    @Resource
    IUserRemote userRemote;
    @Resource
    IOrderRemote orderRemote;

    /**
     * 获取合同分页
     */
    @PostMapping(value = "getContractPage")
    @NotNull({"page", "limit"})
    public ReturnData<PageData<ContractBody>> getContractPage(ContractBody query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<ContractBody> pageData = contractService.getContractPage(getLoginUser(), query, page, limit);
        return jsonView(SUCCESS_CODE, "获取成功", pageData);
    }

    /**
     * 获取或生成电子合同
     */
    @PostMapping(value = "saveOrGetTransitPromise")
    @NotNull("transitOrderId")
    public ReturnData<ContractBody> saveOrGetTransitPromise(@Explain("运单ID") String transitOrderId) {
        ContractBody contractBody = contractService.saveOrGetTransitPromise(transitOrderId);
        return jsonView(true, "获取成功", contractBody);
    }

    /**
     * 签订合同
     */
    @PostMapping(value = "signContract")
    @NotNull({"transitOrderId"})
    @UserTarget({UserType.shipperUser, UserType.truckerUser})
    public ReturnData<Object> signContract(@Explain("运单ID") String transitOrderId, @Explain("用户ID") String accountId) {
        if (accountId == null) accountId = getLoginUser().getId();
        Account account = ParamUtil.isSuccess(userRemote.getAccountById(accountId));
        Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(account.getOrganizeId()));
        //需验证有无权限
        contractService.signTransitPromise(getLoginUser(), transitOrderId, organize);
        return jsonView(SUCCESS_CODE, "签订成功");
    }

    /**
     * 作废合同
     */
    @PostMapping(value = "cancellationContract")
    @NotNull({"transitOrderId"})
    @UserTarget(UserType.platformUser)
    public ReturnData<Object> cancellationContract(@Explain("运单ID") String transitOrderId) {
        TransitOrder transitOrder = ParamUtil.isSuccess(orderRemote.getTransitOrderById(transitOrderId));
//        if (!Objects.equals(getLoginUser().getOrganizeId(), transitOrder.getPlatId())) {
//            return jsonView(false, "无权操作");
//        }
        ContractBody contractBody = contractService.saveOrGetTransitPromise(transitOrderId);
        if (contractBody != null) {
            contractBody.setContractState(ContractBody.ContractState.invalid);
            contractBody.setUpdateTime(new Date());
            contractBody.setUpdateUserId(getLoginUser().getId());
            contractService.updateById(contractBody);
        }
        return jsonView(true, "操作成功");
    }

    /**
     * 下载运单合同
     */
    @PostMapping("genContractPdf")
    @NotNull({"transitOrderId"})
    public ReturnData<Object> genContractPdf(String transitOrderId) {
        TransitOrder transitOrder = ParamUtil.isSuccess(orderRemote.getTransitOrderById(transitOrderId));
        String html = PlatRequest.selfGet(getLoginUser().getToken(), "/data/views/contractHtml", MapUtil.generate(map -> {
            map.put("transitOrderId", transitOrderId);
            map.put("pdfPrint", true);
        }));
        String filePath = AppUtil.getTemporaryPath(temporaryPath) + "Contract\\";
        if (!new File(filePath).exists()) new File(filePath).mkdir();
        String pdfPath = String.format("%s%s.pdf", filePath, transitOrder.getTransportNo());
        boolean success = PdfUtil.html2Pdf(ArrayUtil.initList(html), pdfPath);
        if (!success) return jsonView(false, "生成合同PDF失败！请重试！");
        MultipartFile multipartFile = FileDealUtil.getMultipartFile(new File(pdfPath));
        MinIoUploadResDTO upload = minOssService.upload(multipartFile, MinOssService.UploadType.temp.path, "contract");
        Map<String, String> retMap = new HashMap<>();
        retMap.put("fileName", transitOrder.getTransportNo());
        retMap.put("fileUrl", upload.getMinFileUrl());
        return jsonView(true, "临时路径生成成功，请尽快下载！", retMap);
    }
}
